<template>
  <div class="edit-container">
    <!-- 导航条 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.go(-1)" />
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        width="120"
        height="120"
        round
        fit="cover"
        :src="userInfo.photo"
      />
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 信息展示 -->
    <van-cell-group>
      <van-cell
        title="姓名"
        :value="userInfo.name"
        is-link
        @click="editNameClick"
      />
      <van-cell
        title="性别"
        :value="userInfo.gender ? '女' : '男'"
        is-link
        @click="showPopup = true"
      />
      <van-cell
        title="生日"
        :value="userInfo.birthday"
        ref="nameFiled1"
        is-link
        @click="
          showDatePicker = true
          currentDate = new Date(userInfo.birthday)
        "
      />
    </van-cell-group>

    <!-- 编辑姓名弹窗 -->
    <!--1 双向绑定弹窗显示隐藏 -->
    <van-dialog
      v-model="showDialog"
      title="编辑姓名"
      show-cancel-button
      @confirm="updateName"
    >
      <!--2 双向绑定输入框 -->
      <van-field v-model="newName" ref="input" placeholder="请输入姓名" />
    </van-dialog>

    <!--3 编辑性别弹窗 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-arrow
        @click-left="showPopup = false"
      />
      <van-cell title="男" is-link @click="updteGender(0)" />
      <van-cell title="女" is-link @click="updteGender(1)" />
    </van-popup>

    <!--4 修改生日 -->
    <van-popup position="bottom" v-model="showDatePicker">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showDatePicker = false"
        @confirm="updateBirthday"
      />
    </van-popup>

    <!-- 5.图片裁切 -->
    <div class="cropper" v-show="showCropper">
      <vueCropper
        ref="cropper"
        :img="img"
        autoCrop
        autoCropWidth="150"
        autoCropHeight="150"
      ></vueCropper>
      <van-button type="primary" @click="showCropper = false">取消</van-button>
      <van-button type="info" @click="updatePhoto">确认</van-button>
    </div>
  </div>
</template>

<script>
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
// 导入接口
import { editUserInfo } from './user.js'
import { editUserPhoto } from './user.js'

import * as moment from 'moment'
// 导入vue-cropper裁切组件
import { VueCropper } from 'vue-cropper'

export default {
  name: 'edit',
  components: {
    VueCropper
  },
  data () {
    return {
      showDialog: false,
      newName: '',
      showPopup: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2035, 10, 1),
      currentDate: new Date(),
      showDatePicker: false,
      img: '', //要裁切的图片
      showCropper: false //裁切盒子显示/隐藏
    }
  },
  methods: {
    // 1.点击修改名字按钮
    editNameClick () {
      // 弹出dialog弹出
      ;(this.showDialog = true),
        // 输入框默认要是当前用户名字
        (this.newName = this.userInfo.name)
      // 输入框默认称为焦点  原生的DOM.focus
      // this.$refs.input.focus()
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    // 2.dialog弹窗comfirm
    updateName () {
      // 2.1调用接口
      editUserInfo({ name: this.newName }).then(res => {
        // console.log(res)
        // 2.2弹窗提示
        this.$toast.success('更新成功')
        // 2.3更新vuex
        this.$store.commit('updateUserInfo', {
          ...this.userInfo,
          name: this.newName
        })
      })
    },
    // 3.修改性别
    updteGender (gender) {
      editUserInfo({ gender }).then(res => {
        // 1.弹窗提示
        this.$toast.success('更新成功')
        // 2.隐藏popup弹窗
        this.showPopup = false
        // 3.更新vuex
        this.$store.commit('updateUserInfo', {
          ...this.userInfo,
          gender
        })
      })
    },
    //4.修改生日
    updateBirthday () {
      // console.log( this.currentDate );
      //转换日期格式
      let birthday = moment(this.currentDate).format('YYYY-MM-DD')
      editUserInfo({ birthday }).then(res => {
        //(1)弹窗提示
        this.$toast.success('更新成功!')
        //(2)更新vuex数据
        this.$store.commit('updateUserInfo', {
          ...this.userInfo,
          birthday
        })
        //(3)关闭弹窗
        this.showDatePicker = false
      })
    },

    // 5.选择文件
    afterRead (file) {
      // 此时可以自行将文件上传至服务器
      // console.log(file);
      // console.log(file.content); //base64
      // console.log(file.file); // 文件对象（原生DOM获取的就是这个）
      console.log(URL.createObjectURL(file.file))

      // 1.设置裁切图片的路径
      this.img = file.content
      // 2.显示裁切盒子
      this.showCropper = true
    },

    // 6.获得裁切后的图片
    updatePhoto () {
      //1. 获取截图的blob数据
      this.$refs.cropper.getCropBlob(data => {
        // do something
        // console.log(data)
        // 2.上传formData对象
        // 1.生成formdata对象
        let fd = new FormData()
        fd.append('photo', data)
        // 2.提交文件到服务器
        editUserPhoto(fd).then(res => {
          console.log(res)
          //(2.1)弹窗提示
          this.$toast.success('更新成功!')
          // (2.2)隐藏裁切框
          this.showCropper = false
          //(2)更新vuex数据
          this.$store.commit('updateUserInfo', {
            ...this.userInfo,
            photo: res.data.data.photo
          })
        })
      })
    }
  },
  computed: {
    // 使用对象展开运算符将此对象混入到外部对象中
    ...mapState(['userInfo'])
  }
}
</script>

<style lang="less">
.edit-container {
  .van-nav-bar__content {
    background-color: #0099fa;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
    .van-nav-bar__text {
      color: #fff;
    }
  }

  // 头像
  .avatar {
    display: flex;
    height: 150px;
    justify-content: center;
    align-items: center;
    // 文件上传盒子
    .van-uploader {
      position: absolute;
      opacity: 0;
      width: 120px;
      height: 120px;
      .van-uploader_upload {
        width: 120px;
        height: 120px;
      }
    }
  }
  /* 裁切盒子 */
  .cropper {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    .van-button--primary {
      position: absolute;
      left: 0;
      bottom: 0;
    }
    .van-button--info {
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>
